package function;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;

import util.JdbcUtil;

public class Open 
{
	private Connection conn = null;
	private PreparedStatement ps = null;
	private ResultSet rs = null;
	private int id;
	private LinkedList<c> func = null;

	public Open(int id)
	{
		this.id = id;
		int count = 0;
		conn = JdbcUtil.getConnection();
		String table = "function_table";
		String sql = "insert into "+table+" values("+id+",0)";
		String find = "select SchID from "+table+" where SchID="+id;
		try {
			ps = conn.prepareStatement(find);
			rs = ps.executeQuery();
			while(rs.next())
			{
				count = 1;
//				System.out.print("there is already the file exist");
			}
			if(count == 0)
			{
				ps = conn.prepareStatement(sql);
				ps.executeUpdate();
			}			
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			JdbcUtil.release(conn, ps, rs);
		}
	}
	public void msg(int i)
	{
		conn = JdbcUtil.getConnection();
		String table = "function_table";
		String sql = null;
		if(i==1)
		{
			sql = "update "+table+" set msg=1 where SchID="+id;
		}
		else
		{
			sql = "update "+table+" set msg=0 where SchID="+id;
		}
		try {
			ps = conn.prepareStatement(sql);
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			JdbcUtil.release(conn, ps, rs);
		}
	}
	/////the two method can be conformed to be a method,why I wrote like this is for a good view.

	
	@SuppressWarnings("unchecked")
	public LinkedList<c> getFunc() 
	{
		conn = JdbcUtil.getConnection();
		String table = "function_table";
		String sql = "select * from "+table;
		func = new LinkedList();
		try {
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while(rs.next())
			{
				c c = new c(rs.getInt(1),rs.getInt(2));
				func.add(c);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			JdbcUtil.release(conn, ps, rs);
		}
		return func;
	}
	
	public int have(int id)
	{
		for(int i = 0;i<getFunc().size();i++)
		{
			if(id == getFunc().get(i).getId())
			{
				return i;
			}
		}
		return 1000;
	}
	
//	public static void main(String[] args) 
//	{
//		Open a = new Open(19870001);
//		System.out.println("a.cost(1) is ready");
//		a.msg(1);
//		System.out.println("a.cost(0) is ready");
//		System.out.println(a.getFunc().get(a.have(123)).getMsg());
//	}
}


